package lab.chapter;

import java.util.Collections;
import java.util.Set;

/**
 * DFA 状态
 */
public class DFAState extends State {
    // 组成 DFAState 的NFAState集合
    private Set<State> states = null;

    public DFAState(Set<State> states) {
        this.states = states;
    }

    protected Set<State> states() {
        return Collections.unmodifiableSet(states);
    }

    /**
     * 提供一个对象作为迁移条件，看能否迁移到下一个状态
     * @param object 词法分析对象
     * @return 状态
     */
    protected DFAState getNextState(Object object) {
        for (Transition transition : transitions()) {
            if (transition.match(object)) {
                return (DFAState) getState(transition);
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuilder rtn = new StringBuilder(super.toString());
        rtn.append("\tNFA states: ");
        int i = 0;
        for (State state : states) {
            if (i++ > 0) {
                rtn.append(", ");
            }
            rtn.append(state.getName());
            if (state.getGrammarNode() != null && state.getGrammarNode().isNamedNode()) {
                rtn.append("(").append(state.getGrammarNode().getName()).append(")");
            }
        }
        rtn.append('\n');
        return rtn.toString();
    }

    /**
     * 只要其中现代战争 NFA是一个接受状态，该 DFAState就是接受状态
     * @return bool
     */
    @Override
    public boolean isAcceptable() {
        for (State state : states) {
            if (state.isAcceptable()) {
                return true;
            }
        }
        return false;
    }
}
